import {
  batchCheckBannedWord,
  batchCheckPrice,
  batchCheckProductInfo,
  batchPublic,
  DianxiaomiProductInfo,
} from '@/api/product';
import config from '@/config';
import useLocalStorage from '@/entrypoints/hook/useLocalStorage';
import { getAllProductInfos } from '@/lib/dianxiaomi';
import { delay } from '@/lib/utils';
import { useSettingsStore } from '@/store';
import { use } from 'marked';
import { toast } from 'sonner';
import { OperationMessageType } from '@/store/message';
import { useMessage } from './useDiaoxiaomiMessage';

export function usePublic() {
  const publicInterval = useSettingsStore((state) => state.publicSettings.publicInterval);
  const [isPaused, setIsPaused] = useState(true);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const [storageValue, setStorageValue] = useLocalStorage(config.dianxiaomi.publicKey, {
    // 设置默认的发布数量
    publicMaxCount: 50,
    // 设置已经发布的数量
    publicCount: 0,
  });
  const storageValueRef = useRef(storageValue);
  const offlineProductInfos = useRef<DianxiaomiProductInfo[]>([]);
  const { addMessage } = useMessage();
  const appConfig = useAppConfig();

  useEffect(() => {
    storageValueRef.current = storageValue;
  }, [storageValue]);

  // 刚开始时把已经发布的数量设置为 0
  useEffect(() => {
    setStorageValue((prev) => {
      return {
        ...prev,
        publicCount: 0,
      };
    });
  }, []);

  // 获取代发布产品中的所有信息
  useEffect(() => {
    async function getAllOfflineProductInfos() {
      const productInfos = await getAllProductInfos();
      offlineProductInfos.current = productInfos;
    }
    getAllOfflineProductInfos();
  }, []);

  const publicProduct = useCallback(async (productInfo: DianxiaomiProductInfo) => {
    const checkPriceResult = await batchCheckPrice({
      ids: productInfo.idStr,
    });
    if (checkPriceResult.code !== 0) {
      throw new Error(`价格检查失败: ${checkPriceResult.msg}`);
    }

    const checkBannedWordResult = await batchCheckBannedWord({
      productIds: productInfo.idStr,
    });
    if (checkBannedWordResult.code !== 0) {
      throw new Error(`违禁词检查失败: ${checkBannedWordResult.msg}`);
    }

    const checkProductInfoResult = await batchCheckProductInfo({
      ids: productInfo.idStr,
    });
    if (checkProductInfoResult.code !== 0) {
      throw new Error(`产品信息检查失败: ${checkProductInfoResult.msg}`);
    }

    const publicResult = await batchPublic({
      ids: productInfo.idStr,
    });
    if (publicResult.code !== 0) {
      throw new Error(`发布失败: ${publicResult.msg}`);
    } else {
      if (publicResult.data.failList.length > 0) {
        throw new Error(`发布失败: ${publicResult.data.failList[0].msg}`);
      }
    }
  }, []);

  const intervalPublicProduct = useCallback(() => {
    // 重新启动时把之前的定时器清理掉
    if (intervalRef.current) clearInterval(intervalRef.current);
    setIsPaused(false);
    intervalRef.current = setInterval(async () => {
      if (storageValueRef.current.publicCount >= storageValueRef.current.publicMaxCount) {
        pause();
        return;
      }
      if (offlineProductInfos.current.length === 0) {
        toast.info('没有待发布商品');
        pause();
        return;
      }
      const productInfo = offlineProductInfos.current.shift();
      if (productInfo) {
        const skuInfo = productInfo.variations[0].extCode;
        try {
          await publicProduct(productInfo);
          setStorageValue((prev) => {
            return {
              ...prev,
              publicCount: prev.publicCount + 1,
            };
          });
          addMessage({
            type: OperationMessageType.success,
            category: appConfig.topMessageCategoryName,
            message: `${skuInfo} 产品发布成功`,
          });
        } catch (error) {
          // toast.error(`产品发布失败: ${(error as Error).message}`);
          addMessage({
            type: OperationMessageType.error,
            category: appConfig.topMessageCategoryName,
            message: `${skuInfo} 产品发布失败: ${(error as Error).message} `,
          });
          await setStorageValue((prev) => {
            return {
              ...prev,
              publicCount: prev.publicCount + 1,
            };
          });
        }
      }
    }, publicInterval);
  }, [publicInterval, publicProduct]);

  const pause = useCallback(() => {
    setIsPaused(true);
    if (intervalRef.current) clearInterval(intervalRef.current);
  }, []);

  return {
    publicProduct,
    intervalPublicProduct,
    pause,
    isPaused,
    storageValue,
    setStorageValue,
    offlineProductInfos,
  };
}
